package com.autologistics.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.autologistics.model.Goods;
import com.autologistics.model.Ordertable;

public class OrderTableDaoImpl implements OrderTableDao{
	HibernateTemplate hibTemplate;

	public HibernateTemplate getHibTemplate() {
		return hibTemplate;
	}

	public void setHibTemplate(HibernateTemplate hibTemplate) {
		this.hibTemplate = hibTemplate;
	}
	/**
	 * @return ������ or null
	 * @author cl
	 */
	public List<Ordertable> listAll(){
		String hql = "from Ordertable";
		List<Ordertable> list = hibTemplate.find(hql);
		if (!list.isEmpty()){
			return list;
		}else{
			return null;
		}
	}

	@Override
	public Ordertable getByOrderID(String orderID) {
		// TODO Auto-generated method stub
		String hql = "from Ordertable where orderId=?";
		List<Ordertable> list = hibTemplate.find(hql,orderID);
		if (!list.isEmpty()){
			return list.get(0);
		}else{
			return null;
		}
	}

	@Override
	public void updata(Ordertable orderTable) {
		// TODO Auto-generated method stub
		hibTemplate.update(orderTable);
	}
	public int save(Ordertable orderTable) {
		return (Integer) hibTemplate.save(orderTable);
	}
	public Ordertable getById(int id){
		String hql="from Ordertable where id=?";
		List<Ordertable> list = hibTemplate.find(hql,id);
		if (!list.isEmpty()){
			return list.get(0);
		}else{
			return null;
		}
	}
	public List<Ordertable> queryForOnePage(final int offset, final int length){
		String hql = "from Ordertable";
		Session session = hibTemplate.getSessionFactory().openSession();
		Query q = session.createQuery(hql);  
	    q.setFirstResult(offset);  
	    q.setMaxResults(length); 
	    List<Ordertable> list=q.list();
	    session.close();
		if (!list.isEmpty()){
			return list;
		}else{
			return null;
		}
	}
	
	public List<Goods> GoodsCount(final int offset, final int length){
		String hql = "select b from Goodsorder as g left join g.goods as b group by b.name order by count(b.name) desc";
		hibTemplate.find(hql);
		Session session = hibTemplate.getSessionFactory().openSession();
		Query q = session.createQuery(hql);  
	    q.setFirstResult(offset);  
	    q.setMaxResults(length); 
	    List<Goods> list=q.list();
	    session.close();
		if (!list.isEmpty()){
			return list;
		}else{
			return null;
		}
	}
}
